<?php
namespace App\Models\Account;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Request;
use DB;
use \Illuminate\Support\Facades\Input;


class PlayerActModel extends  Model{

    protected $table='account_info';

	public function paginate()
    {
    	$perPage = Request::get('per_page', 20);

        $page = Request::get('page', 1);

        $start = ($page-1)*$perPage;

        $tableAccount = 'account_info';
        $rw = \DB::connection('mysql_bgac')->table($tableAccount);
        self::SourceCondition($rw);
        // $rw->orderBy('account', 'DESC');
        $total = $rw->get()->count();
        $rw = $rw->skip($start)->take($perPage);
        $data = $rw->get();
        $data = $data->toArray();

        // $data = json_decode($data, true);
        \Log::debug(__METHOD__, [$rw->toSql(), Input::all()]);
        $list = static::hydrate($data);

        $paginator = new LengthAwarePaginator($list, $total, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function with($relations)
    {
        return new static;
    }

    public function getConnectionName(){
        return 'mysql_bgac';
    }


    public static function detailPlayer($accountId){

        $tableAccount = 'account_info';
        $data = \DB::connection('mysql_bgac')->table($tableAccount)->where('account',$accountId)->first();
       
        $data = (array)$data;
        $player_lists = json_decode($data['playerList'], true)?:[];
        $data['playerList'] = [];
        //$data['playerList'] = DB::connection('mysql_bgsi')->table('player_info')->where('account', $accountId)->get(['playerId', 'area as areaId', 'name as playerName','level', 'diamond'])->map(function($obj){return (array)$obj;})->toArray();
        foreach($player_lists as $i => $obj) {
            if (!is_array($obj) ) {
                continue;
            }
            $obj['areaId'] = $obj['area'];
            $obj['playerName'] = $obj['player_name'];
            $obj['playerId'] = $obj['player_id'];

            $data['playerList'][] = $obj;
        }

        $data['area_info'] = \App\Models\Area::areaAll();
        $data['area_info'] = array_column($data['area_info'], 'name', 'areaId');
       

        $style = $data['is_seal_number'] == 1 ? 'success':'default';
        $alias = $data['is_seal_number'] == 1 ? 'On':'Off';
        $data['seal_alias'] = '<span class="label label-'.$style.'">'.$alias.'</span>';
        
        $area = \Request::get("area") ?: $data['lastAreaId'];
        $data['area'] = $area;
        $rtn_info = [];
        
        \App\Models\SendSocketToGame::SendAction(function($socket)use(&$rtn_info, $data, $area){
            $msg['msgid'] = \App\Service\MessageDef::http_plat_game_request;
            $msg["area"] =  \App\Models\Area::getPhysicsArea($area);
            $msg['game_msgid'] = \App\Service\MessageDef::g2p_player_info_req;
            $msg["playerId"] = 1;
            $msg["game_msg"] = [  
                'account' => $data['account'],
            ];
            $ret = $socket->send($msg);
            \Log::debug('send single player mail', []);

            $rtn_info = $socket->ReadHttpReponse();
            //\Log::debug('read mail reponse data', [$msg,$rtn_info]);
        });

        $data['player_info'] = $rtn_info['data'];
        $data['player_info']['create_time'] = date("Y-m-d H:i:s",  $data['player_info']['create_time']);
        $data['player_info']['ip'] = $data['ip'];
        \Log::Debug(__METHOD__, [$rtn_info, $data]);
        return $data;
    }

    // 获取玩家账号id
    public static function getAccountByName($name = '', $unsetFld = ''){
        if (!$name) {
            !$unsetFld && $unsetFld = 'playerName';
            $name = Input::get($unsetFld);
            if (!$name){
                return;
            }
        }
        $op = DB::connection('mysql_bgac')->table('account_info')->where('playerList', 'like', "%$name%");
        $list = $op->get()->map(function($obj){return (array)$obj;})->toArray();
        
        $account = array_column($list, 'account') ?: [];

        //$arr = Input::all();
        //$arr['account'] = $account;
        //$arr[$unsetFld] = NULL;
        //Input::replace($arr); 
        //var_dump($account);exit;
        return $account ?: [];
    }
    
    // 获取用户信息
    public static function getPlayerInfo($playerId, $area = 0){
        if (!$playerId) {
            return [];
        }
        $db = \DB::connection('mysql_bgsi')->table('player_info')->where('playerId', $playerId);
        
        if ($area) {
            $db->where('area', $area);
        }

        $data = $db->first();
        if (!$data){
            return [];
        }

        $ret = (array)$data;
        return $ret;
    }

    public static function SourceCondition(&$rw)
    {
        $cond = Request::all();
        if ($cond['account']){
            $rw->where("account", $cond["account"]?:0);
        }
        $area =  $cond['area']?:$cond['lastAreaId'];
        if ($area){
            $area = $area == -1 ? 0 : $area;
            $rw->where("lastAreaId", $area);
        }
        if ($cond['lastPlayerId']){
            if ($cond['lastPlayerId'] == '>0') {
                $rw->where("lastPlayerId", '>', 0);
            } else {
                $rw->where("lastPlayerId", $cond['lastPlayerId']?:0);
            }
        }

        if ($cond['mainChannel']){
            $rw->where("mainChannel", $cond['mainChannel']?:0);
        }

        if ($cond['playerName'] ) {
            $rw->where('playerList', 'like', "%{$cond['playerName']}%");
        }

        if ($cond['udid'] ) {
            $rw->where('udid', 'like', "{$cond['udid']}%");
        }
        
        $createTime = Input::get('createTime');
        if ($createTime) {
            $createTime['start'] && $rw->whereRaw("createTime >= '{$createTime['start']}'");
            $createTime['end'] && $rw->whereRaw("createTime <= '{$createTime['end']}'");
        }
        $lastLoginTime= Input::get('lastLoginTime');
        if ($lastLoginTime) {
            $lastLoginTime['start'] && $rw->where('lastLoginTime', '>=', ($lastLoginTime['start']) );
        }

        if ($cond['_sort']) {
            $rw->orderby($cond['_sort']['column'], $cond['_sort']['type']);
        }
    }

    //
    public static function DisableChat($area, $player_id, $timestamp = 0)
    {
        $data['player_id'] = $player_id;
        $data['timestamp'] = $timestamp;
        \App\Models\SendSocketToGame::SendAction(function($socket)use(&$rtn_info, $data, $area){
            $msg['msgid'] = \App\Service\MessageDef::http_plat_game_request;
            $msg["area"] = \App\Models\Area::getPhysicsArea($area);
            $msg['game_msgid'] = \App\Service\MessageDef::http_plat_diable_chat_request;
            $msg["playerId"] = $data['player_id'];
            $msg["game_msg"] = [  
                'player_id' => $data['player_id'],
                'timestamp' => $data['timestamp'],
            ];
            $ret = $socket->send($msg);
            \Log::debug('send single player mail', []);

            $rtn_info = $socket->ReadHttpReponse();
            //\Log::debug('read mail reponse data', [$msg,$rtn_info]);
        });
        return $rtn_info;
    }

    public static function RoleSeal($area, $player_id, $role_seal = 0){
        $data['player_id'] = $player_id;
        $data['role_seal'] = $role_seal;
        \App\Models\SendSocketToGame::SendAction(function($socket)use(&$rtn_info, $data, $area){
            $msg['msgid'] = \App\Service\MessageDef::http_plat_game_request;
            $msg["area"] = \App\Models\Area::getPhysicsArea($area); 
            $msg['game_msgid'] = \App\Service\MessageDef::http_plat_role_seal_request;
            $msg["playerId"] = $data['player_id'];
            $msg["game_msg"] = [  
                'player_id' => $data['player_id'],
                'role_seal' => $data['role_seal'],
            ];
            $ret = $socket->send($msg);
            \Log::debug('send single player mail', []);

            $rtn_info = $socket->ReadHttpReponse();
            //\Log::debug('read mail reponse data', [$msg,$rtn_info]);
        });
        return $rtn_info;

    }

    // 穿透到账户下的条件
    public static function getFollowAccountCond($obj, $day_i, $str) {
        
        //\Log::debug("[PLAYER][getFollowAccountCond]RETAIN_TIME[$obj->retain_time]");
        $obj->retain_time = intval($obj->retain_time);
        if ($obj->retain_time == 0 ) {
            return $str;
        }

        $current_time = intval($obj->retain_time) + $day_i * 86400;
        $cond = [
            'createTime' => ['start' => date('Y-m-d', $obj->retain_time), 'end'=> date('Y-m-d', $obj->retain_time + 86400)],
            'lastPlayerId' => '>0',
        ];

        if ($day_i > 0) {
            $cond['lastLoginTime'] =  ['start' =>date('Y-m-d', $current_time)];
        }
        $href = \App\Service\Common::build_url_query('/admin/player/list-account'
            , $cond);
        $rtn = '<a href ="'. $href . '">' .$str. '</a>';
        return $rtn;
    }

    //
    public static function getAllDevice() {
        return [

        ];
    }

    // 获取account 列表
    public static function getAccountList($account_ids) {
        $list = \DB::connection("mysql_bgac")->table('account_info')
            ->whereIn('account', array_unique($account_ids?:[]))->get();
        $rtn_list = [];
        foreach ($list as $obj) {
            $rtn_list[$obj->account] = (array)$obj;
        }
        // \Log::debug("[GET_ACCOUNT_LIST][BY_ACCOUNT_IDS]", $rtn_list);
        return $rtn_list;
    }

    public static function PromoteGm($area, $player_id, $gm_value = 0)
    {
        $data['player_id'] = $player_id;
        $data['gm_value'] = $gm_value;
        \App\Models\SendSocketToGame::SendAction(function($socket)use(&$rtn_info, $data, $area){
            $msg['msgid'] = \App\Service\MessageDef::http_plat_game_request;
            $msg["area"] = \App\Models\Area::getPhysicsArea($area); 
            $msg['game_msgid'] = \App\Service\MessageDef::http_plat_promote_gm_request;
            $msg["playerId"] = $data['player_id'];
            $msg["game_msg"] = [  
                'player_id' => $data['player_id'],
                'gm_value' => $data['gm_value'],
            ];
            $ret = $socket->send($msg);
            \Log::debug('promote player gm', []);

            $rtn_info = $socket->ReadHttpReponse();
            //\Log::debug('read mail reponse data', [$msg,$rtn_info]);
        });
        return $rtn_info;
    }

    public static function clearRank($area, $player_id, $gm_value = 0) {
        $data['player_id'] = $player_id;
        $data['gm_value'] = $gm_value;
        \App\Models\SendSocketToGame::SendAction(function($socket)use(&$rtn_info, $data, $area){
            $msg['msgid'] = \App\Service\MessageDef::http_plat_game_request;
            $msg["area"] = \App\Models\Area::getPhysicsArea($area); 
            $msg['game_msgid'] = \App\Service\MessageDef::http_plat_clear_rank_request;
            $msg["playerId"] = $data['player_id'];
            $msg["game_msg"] = [  
                'player_id' => $data['player_id'],
                'gm_value' => $data['gm_value'],
            ];
            $ret = $socket->send($msg);
            \Log::debug('clear rank gm', [\App\Service\MessageDef::http_plat_clear_rank_request, $ret]);

            $rtn_info = $socket->ReadHttpReponse();
            //\Log::debug('read mail reponse data', [$msg,$rtn_info]);
        });
        return $rtn_info;       
    }

    // 实现自定义导出数据源
    public static function getCustomExportData($perPage = 0)
    {
        $perPage = $perPage ?:Request::get('per_page', 50000);
        $page = Request::get('page', 1);
        $start = ($page-1)*$perPage;

        $tableAccount = 'account_info';
        $rw = \DB::connection('mysql_bgac')->table($tableAccount);
        self::SourceCondition($rw);
        // $rw->orderBy('account', "DESC");
        if ( $perPage) {
            $rw = $rw->skip($start)->take($perPage);
        }
        // \Log::debug(__METHOD__, ['getCustomExportData start success!', 'memory'=>round(memory_get_usage()/1024/1024, 2).'MB']);
        $data = $rw->get()->toArray();
        \Log::debug('Export Player', [$start, $rw->toSql()]);
        // $alias_trans_list = \App\Models\Pay\Recharge::GetRechargeAlias();
        // $recharge_json = \App\Models\Pay\Recharge::getAll();
        
        $export_data = [];
        foreach ($data as $obj) {
            $tmp_arr = [];
            foreach(self::getCustomExportHead() as $attr => $value){
                $tmp_arr[$attr] = $obj->{$attr} ?:' ';
            }

            // 覆盖值
            // $conf_one = $recharge_json[$obj->cp_product_id ]?:[];
            // $tmp_arr['game_rmb'] = $conf_one['rmb'];
            
            // $tmp_arr['prop_name'] = $alias_trans_list[$obj->cp_product_id ];

            $export_data[] = $tmp_arr;
        }
        // $export_data[] = self::getCustomExportHead();
        // unset($data);
        \Log::debug(__METHOD__, ['custom define success!', 'export count'=> $rw->count(),'memory'=>memory_get_usage()]);
        return $export_data;
    }

    public static function getCustomExportHead()
    {
        return [
            'account'            =>  'Account',
            'lastPlayerId'            =>  'PlayerId',
            'udid'   =>  'Device',
            
            'ip'  =>  'IP',
            'lastAreaId'    =>  'Area',
        ];
    }
}
